import Vue from 'vue'
import Router from 'vue-router'
import NotFoundComponent from '../components/NotFoundComponent.vue'
const t = com => () => window.IS_MOBILE ? import(`../components/${com}/h5.vue`) : import(`../components/${com}/pc.vue`)
const Home = t('Home')
const Login = t('Login')
const Register = t('Register')

import store from '../store'
import { Auth } from '../utils'

Vue.use(Router)

const router = new Router({
  routes: [
    { // 入口
      path: '/',
      beforeEnter (to, from, next) {
        next(false)
        router.replace('/home')
      }
    },
    {// 首页
      path: '/home',
      name: 'home',
      component: Home,
      meta: {
        requiresAuth: false
      }
    },
    { // 登录
      path: '/login',
      name: 'login',
      component: Login
    },
    { // 登录
      path: '/register',
      name: 'register',
      component: Register
    },
    { // 404
      path: '*',
      name: 'notFound',
      component: NotFoundComponent
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

// 登录态和授权管理  未登录：登录，已经登录：from是当前页
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!Auth.isLogIn()) {
      next({
        name: 'login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

// simple history management
const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)

// 路由控制页脚
router.beforeEach(function (to, from, next) {
  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)

  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit('UPDATE_DIRECTION', 'forward')
    } else {
      store.commit('UPDATE_DIRECTION', 'reverse')
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit('UPDATE_DIRECTION', 'forward')
  }

  if (/\/http/.test(to.path)) {
    let url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})

router.afterEach(function (to) {
  if (process.env.NODE_ENV === 'production') {
    console.log('set', 'page', to.fullPath)
    console.log('send', 'pageview')
  }
})

export default router
